package com.onpositive.wiki2.whole.model;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.RandomAccessFile;

import com.onpositive.compactdata.CompactLongVector;

public class ContentAccess {

	File ps;

	protected RandomAccessFile fl;
	protected CompactLongVector positions;
	protected ByteStringTable tb;

	public ContentAccess(String cat) throws FileNotFoundException, IOException,
			ClassNotFoundException {

		File file = new File(cat);
		ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(
				new FileInputStream(new File(file, "content.cat"))));
		tb = (ByteStringTable) is.readObject();
		is.close();
		//is = new ObjectInputStream(new BufferedInputStream(new FileInputStream(
		positions =new CompactLongVector(new File(file, "content.list"));		
		fl = new RandomAccessFile(new File(file, "content.dat"), "r");
	}

	public String getContent(int id) throws IOException {
		long i = positions.get(id);
		fl.seek(i);
		int readInt = fl.readInt();
		byte[] b = new byte[readInt];
		fl.readFully(b);
		return new String(b, "UTF-8");
	}
	
	public String getContent(String title) throws IOException{
		int id = tb.id(title);
		if (id!=-1){
			return getContent(id);
		}
		return null;
	}

	int lastid;
	public String getTitle(int a) {
		return tb.getName(a);
	}

	public int size() {
		return tb.size();
	}
}
